package com.lft.examsys.model;


import com.lft.examsys.entity.CreditUser;
import com.lft.examsys.entity.User;
import com.lft.examsys.exception.ValidationFailureException;
import com.lft.examsys.exception.ViewChangeException;
import com.lft.examsys.handler.ValidationFailureHandler;
import com.lft.examsys.handler.ValidationHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;

import java.util.Set;

public interface IModel {
    static IModel get() {
        return new Model();
    }

    Set<String> keySet();

    Object put(String key, Object value);

    Object get(Object key);

    default IModel add(String key, Object value) {
        put(key, value);
        return this;
    }

    default IModel err(String msg) {
        put("errMsg", msg);
        return this;
    }

    default IModel info(String msg) {
        put("infoMsg", msg);
        return this;
    }

    default IModel warn(String msg) {
        put("warnMsg", msg);
        return this;
    }

    default void failure(String message) throws ValidationFailureException {
        throw new ValidationFailureException(message);
    }

    IModel valid(boolean valid);

    boolean valid();

    ModelAndView redirectTo(String viewName) throws ViewChangeException;

    ModelAndView forwardTo(String viewName) throws ViewChangeException;

    String currentView();

    ValidationModelAndView validation(String viewName, ValidationHandler valid, ValidationFailureHandler invalid);
    ValidationModelAndView validation(String viewName, ValidationHandler valid);

    default User user() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getPrincipal().equals("anonymousUser") ? null :  ((CreditUser)authentication.getPrincipal()).getUser();
    }
    default void user(User user) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        ((CreditUser)authentication.getPrincipal()).setUser(user);
    }
}
